//
//  JKCountDownButton.m
//  JKCountDownButton
//
//  Created by Jakey on 15/3/8.
//  Copyright (c) 2015年 www.skyfox.org. All rights reserved.
//

#import "Kratos_CountDownButton.h"
#import "UIView+kkk_viewExtionsion.h"

@interface NSTimer (JKCountDownBlocksSupport)
+ (NSTimer *)jkcd_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                           block:(void(^)(void))block
                                         repeats:(BOOL)repeats;
@end


@interface Kratos_CountDownButton(){
    NSInteger _second;
    NSUInteger _totalSecond;
    
    NSTimer *_timer;
    NSDate *_startDate;
    
    CountDownChanging _countDownChanging;
    CountDownFinished _countDownFinished;
    TouchedCountDownButtonHandler _touchedCountDownButtonHandler;
}
@end

@implementation Kratos_CountDownButton
- (void)drawRect:(CGRect)rect
{
    CGFloat width = rect.size.width;
    
    CGFloat height = rect.size.height;
    
    // 简便起见，这里把圆角半径设置为长和宽平均值的1/10
    
    CGFloat radius = (width + height) * 0.05;
    
    
    // 获取CGContext，注意UIKit里用的是一个专门的函数
    
    CGContextRef context =UIGraphicsGetCurrentContext();
    
    // 移动到初始点
    CGContextMoveToPoint(context, radius, 0);
    
    
    // 绘制第1条线和第1个1/4圆弧，右上圆弧
    
    CGContextAddLineToPoint(context, width - radius,0);
    
    CGContextAddArc(context, width - radius, radius, radius, -0.5 *M_PI,0.0,0);
    
    
    
    // 绘制第2条线和第2个1/4圆弧，右下圆弧
    
    CGContextAddLineToPoint(context, width, height - radius);
    
    CGContextAddArc(context, width - radius, height - radius, radius,0.0,0.5 *M_PI,0);
    
    
    
    // 绘制第3条线和第3个1/4圆弧，左下圆弧
    
    CGContextAddLineToPoint(context, radius, height);
    
    CGContextAddArc(context, radius, height - radius, radius,0.5 *M_PI,M_PI,0);
    
    
    
    // 绘制第4条线和第4个1/4圆弧，左上圆弧
    
    CGContextAddLineToPoint(context, 0, radius);
    
    CGContextAddArc(context, radius, radius, radius,M_PI,1.5 *M_PI,0);
    
    
    
    // 闭合路径
    
    CGContextClosePath(context);
    
    // 填充半透明红色
    
    CGContextSetRGBFillColor(context,1.0,1.0,1.0,1.0);
    
    CGContextDrawPath(context,kCGPathFill);
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Kratos_stopCountDown) name:@"stopCountDown" object:nil];

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma -mark touche action
- (void)Kratos_countDownButtonHandler:(TouchedCountDownButtonHandler)touchedCountDownButtonHandler{
    _touchedCountDownButtonHandler = [touchedCountDownButtonHandler copy];
    [self addTarget:self action:@selector(touched:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)touched:(Kratos_CountDownButton*)sender{
    if (_touchedCountDownButtonHandler) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self->_touchedCountDownButtonHandler(sender,sender.tag);
        });
    }
}



#pragma -mark count down method
- (void)Kratos_startCountDownWithSecond:(NSUInteger)totalSecond
{
    _totalSecond = totalSecond;
    _second = totalSecond;
   
    
    __weak typeof(self) weakSelf = self;
    _timer = [NSTimer jkcd_scheduledTimerWithTimeInterval:1.0 block:^{
         typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf timerStart];
    } repeats:YES];
    
    _startDate = [NSDate date];
    _timer.fireDate = [NSDate distantPast];
    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)timerStart {
     double deltaTime = [[NSDate date] timeIntervalSinceDate:_startDate];
    
     _second = _totalSecond - (NSInteger)(deltaTime+0.5) ;

    
    if (_second< 0.0)
    {
        [self Kratos_stopCountDown];
    }
    else
    {
        if (_countDownChanging)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *title = self->_countDownChanging(self,self->_second);
                [self setTitle:title forState:UIControlStateNormal];
                [self setTitle:title forState:UIControlStateDisabled];
            });
        }
        else
        {
            NSString *title = [NSString stringWithFormat:@"%zd秒",_second];
            [self setTitle:title forState:UIControlStateNormal];
            [self setTitle:title forState:UIControlStateDisabled];

        }
    }
}

- (void)Kratos_stopCountDown{
    if (_timer) {
        if ([_timer respondsToSelector:@selector(isValid)])
        {
            if ([_timer isValid])
            {
                [_timer invalidate];
                _second = _totalSecond;
                if (_countDownFinished)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSString *title = self->_countDownFinished(self,self->_totalSecond);
                        [self setTitle:title forState:UIControlStateNormal];
                        [self setTitle:title forState:UIControlStateDisabled];
                    });
                }
                else
                {
                    [self setTitle:@"获取验证码" forState:UIControlStateNormal];
                    [self setTitle:@"获取验证码" forState:UIControlStateDisabled];

                }
            }
        }
    }
}
#pragma -mark block
- (void)Kratos_countDownChanging:(CountDownChanging)countDownChanging{
    _countDownChanging = [countDownChanging copy];
}
- (void)Kratos_countDownFinished:(CountDownFinished)countDownFinished{
    _countDownFinished = [countDownFinished copy];
}
@end

